package com.yb0os1.task;

import com.yb0os1.dto.OrderConditionSearchDTO;
import com.yb0os1.entity.Orders;
import com.yb0os1.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class MyTask {
    @Autowired
    private OrderMapper orderMapper;
    private final Long MAX_LAST_TIME = 15L;

    //每三分钟检查一次 是否存在超时未支付
    @Scheduled(cron = "0 0/3 * * * ?")
    public void timeoutOrder() {
        List<Orders> ordersList = orderMapper.list(OrderConditionSearchDTO.builder()
                .status(Orders.PENDING_PAYMENT)
                .checkPendingPayment(true)
                .build());
        log.info("对全部订单进行检查，是否存在超时未支付、超时未确认的订单：{}", ordersList);
        for (Orders order : ordersList) {
            //处理一直处于未付款的订单
            orderMapper.update(Orders.builder()
                    .id(order.getId())
                    .status(Orders.CANCELLED)
                    .cancelReason("用户超时未支付")
                    .cancelTime(LocalDateTime.now())
                    .build());
        }
    }

    //每天凌晨一点处理是否还存在派送中的订单
    @Scheduled(cron = "0 0 1 * * ? ")
    public void deliveryInProgressOrder(){
        List<Orders> ordersList = orderMapper.list(OrderConditionSearchDTO.builder().status(Orders.DELIVERY_IN_PROGRESS).build());
        for (Orders order : ordersList) {
            //处理凌晨还在派送中的订单
            orderMapper.update(Orders.builder()
                    .id(order.getId())
                    .status(Orders.COMPLETED)
                    .build());
        }
    }
}